﻿#region Copyright (c) 2012-10, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;


namespace Amarok
{
	/// <summary>
	/// This type implements an completable object.
	/// 
	/// The interface methods can be used to complete the object either synchronously or asynchronously. In addition 
	/// the caller can decide whether already available messages should be processed to completion or whether they 
	/// should be discarded.
	/// 
	/// When calling <see cref="IDisposable.Dispose"/> all available messages will be discarded and the method will 
	/// block the calling thread until the object has finally completed. For more control over completion one should 
	/// call <see cref="ICompletable.Complete"/> and optionally wait for completion using the Task returned from 
	/// <see cref="ICompletable.Completion"/>.
	/// </summary>
	public abstract class CompletableObject : IdentifiableObject,
		ICompletable
	{
		// data
		private readonly TaskCompletionSource mCompletionSource = new TaskCompletionSource();
		private readonly Object mSyncComplete = new Object();

		// state
		private volatile Boolean mIsCompleting;


		#region ++ ICompletable Interface ++

		/// <summary>
		/// Gets a Task instance that represents the completion state of the object. This task instance is 
		/// transitioned into the final RunToCompletion state when the object has finally completed.
		/// </summary>
		Task ICompletable.Completion
		{
			get
			{
				return this.Completion;
			}
		}


		/// <summary>
		/// Initiates the asynchronous completion of the object. After calling this method the object will complete 
		/// and its <see cref="Completion"/> task will enter a final state after it has processed or discarded all 
		/// previously available messages.
		/// </summary>
		/// 
		/// <param name="discardAvailableMessages">
		/// True to discard all already available messages. False to process all already available messages to 
		/// completion. Defaults to false.</param>
		void ICompletable.Complete(Boolean discardAvailableMessages)
		{
			this.CompleteObject(discardAvailableMessages);
		}

		#endregion

		#region ++ IDisposable Interface ++

		/// <summary>
		/// When calling <see cref="IDisposable.Dispose"/> all available messages will be discarded and the method 
		/// will block the calling thread until the object has finally completed.
		/// </summary>
		void IDisposable.Dispose()
		{
			this.DisposeObject();
		}

		#endregion

		#region ## Protected Interface ##

		/// <summary>
		/// Gets a boolean value indicating whether the object is completing.
		/// </summary>
		protected Boolean IsCompleting
		{
			get
			{
				return mIsCompleting;
			}
		}

		/// <summary>
		/// Gets a boolean value indicating whether the object is completed.
		/// </summary>
		protected Boolean IsCompleted
		{
			get
			{
				return mCompletionSource.Task.IsCompleted;
			}
		}

		/// <summary>
		/// Gets a Task instance that represents the completion state of the object. This task instance is 
		/// transitioned into the final RunToCompletion state when the object has finally completed.
		/// </summary>
		protected Task Completion
		{
			get
			{
				return mCompletionSource.Task;
			}
		}


		/// <summary>
		/// Initializes a new instance. Sets the object-id to "type-name".
		/// </summary>
		protected CompletableObject()
		{
		}

		/// <summary>
		/// Initializes a new instance. Sets the object-id to "type-name[:instance-name]".
		/// </summary>
		/// 
		/// <param name="instanceName">
		/// The instance-name of this object. Might be null or an empty string.</param>
		protected CompletableObject(String instanceName)
			: base(instanceName)
		{
		}


		/// <summary>
		/// Initiates the asynchronous completion of the object. After calling this method the object will complete 
		/// and its <see cref="Completion"/> task will enter a final state after it has processed or discarded all 
		/// previously available messages.
		/// </summary>
		/// 
		/// <param name="discardAvailableMessages">
		/// True to discard all already available messages. False to process all already available messages to 
		/// completion. Defaults to false.</param>
		protected void CompleteObject(Boolean discardAvailableMessages = false)
		{
			// already completing?
			if (mIsCompleting)
				return;

			lock (mSyncComplete)
			{
				// already completing?
				if (mIsCompleting)
					return;

				// signal that we are completing
				mIsCompleting = true;
			}

			// complete object (guaranteed to be called once)
			Task taskComplete = null;

			try
			{
				taskComplete = OnComplete(discardAvailableMessages);
			}
			catch (Exception exception)
			{
				#region (tracing)
				{
					Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
						"*** WARNING: UNHANDLED EXCEPTION in CompletableObject.OnComplete():" +
						"\r\n  ObjectId: {0}" +
						"\r\n{1}",
						base.ObjectId,
						Helper.FormatException(exception, CultureInfo.InvariantCulture)
					));
				}
				#endregion

				taskComplete = TaskHelper.Completed;
			}

			taskComplete.ContinueWith(task =>
				{
					// signal completion
					mCompletionSource.SignalCompletion();

					try
					{
						OnCompleted();
					}
					catch (Exception exception)
					{
						#region (tracing)
						{
							Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
								"*** WARNING: UNHANDLED EXCEPTION in CompletableObject.OnCompleted():" +
								"\r\n  ObjectId: {0}" +
								"\r\n{1}",
								base.ObjectId,
								Helper.FormatException(exception, CultureInfo.InvariantCulture)
							));
						}
						#endregion
					}
				},
				TaskScheduler.Default);
		}

		/// <summary>
		/// When calling <see cref="IDisposable.Dispose"/> all available messages will be discarded and the method 
		/// will block the calling thread until the object has finally completed.
		/// </summary>
		protected void DisposeObject()
		{
			this.CompleteObject(discardAvailableMessages: true);
			this.Completion.Wait();
		}

		#endregion

		#region ## Overrideable Methods ##

		/// <summary>
		/// An overrideable method that allows derived types to implement custom completion logic. Derived types
		/// should implement the completion logic in a non-blocking way, meaning this method should return as soon
		/// as possible. If the completion logic requires some long running operations, then those operations should 
		/// be run asynchronous in the background and the returned task should be used to signal final completion.
		/// 
		/// This method is guaranteed to be called once.
		/// </summary>
		/// 
		/// <param name="discardAvailableMessages">
		/// True to discard all already available messages. False to process all already available messages to 
		/// completion. Defaults to false.</param>
		/// 
		/// <returns>
		/// A Task instance that represents the state of the custom completion logic. This task instance should be 
		/// transitioned into the final RunToCompletion state when the custom completion logic has finished.</returns>
		protected virtual Task OnComplete(Boolean discardAvailableMessages)
		{
			// default implementation
			return TaskHelper.Completed;
		}

		/// <summary>
		/// An overrideable method that allows derived types to implement custom cleanup logic. The cleanup method 
		/// is called at last after the object run to completion.
		/// 
		/// This method is guaranteed to be called once.
		/// </summary>
		protected virtual void OnCompleted()
		{
			// default implementation
		}

		#endregion

	}
}
